package com.kmvc.message.lock;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.kmvc.message.encryption.Encryption;
import com.kmvc.message.lock.LockPatternView.Cell;
import com.kmvc.message.lock.LockPatternView.DisplayMode;
import com.kmvc.message.lock.LockPatternView.OnPatternListener;
import com.kmvc.message.activity.GesturePWDCreateActivity;
import com.kmvc.message.activity.LoginActivity;
import com.kmvc.message.activity.MainTab;
import com.kmvc.message.activity.MessageApplication;
import com.kmvc.message.R;
import com.kmvc.message.service.MessageService;
import com.kmvc.message.tools.WebService;

//import android.util.Log;

public class LockMainActivity extends Activity implements OnClickListener {
	private LockPatternView lockPatternView;
	private TextView btn_set_pwd, btn_reset_pwd, tel;
	private TextView messagetip;
	private ProgressDialog progress;
	// private Button btn_check_pwd;
	public boolean flag = true;
	private int wrongcount = 4;
	private String pwd = "", pone = "";
	private SharedPreferences shp;
	private Handler handler = new Handler();
	private Handler handler1 = new Handler();
	private Handler handlers = new Handler();
	private String result = "", result1 = "";

	public void onCreate(Bundle savedInstanceState) {
		super.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lockmainnew);
		
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		
		Intent intent = getIntent();
		try {
			pone = "" + intent.getStringExtra("PhoneNumber");
			MessageApplication application=(MessageApplication)this.getApplication();
			application.phonenum=pone;
		} catch (Exception e) {

			e.printStackTrace();
			pone = "";
		}

		flag = intent.getBooleanExtra("flag", true);
		lockPatternView = (LockPatternView) findViewById(R.id.lpv_lock);
		btn_reset_pwd = (TextView) findViewById(R.id.btn_reset_pwd);
		messagetip=(TextView)findViewById(R.id.messagetip);
		btn_set_pwd = (TextView) findViewById(R.id.btn_set_pwd);
		tel = (TextView) findViewById(R.id.tel);
		
		if (flag == false) {
			Toast.makeText(LockMainActivity.this, "请先绘制原密码", Toast.LENGTH_LONG)
					.show();
		}
		tel.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
		SharedPreferences shps = getSharedPreferences("phonenumber", 0);
		String teltString = shps.getString("tel",
				getResources().getString(R.string.tel));
		if (teltString.startsWith("技术")) {
			tel.setText(teltString);
		} else {
			tel.setText(getResources().getString(R.string.tel));
		}

		String oldpwd = "";
		shp = getSharedPreferences("lock_pwd", 0);
		try {
			oldpwd = shp.getString("lock_pwd", "");
		} catch (Exception e) {
			e.printStackTrace();

		}
		if (oldpwd.equals("")) {
			btn_set_pwd.setVisibility(View.GONE);
			btn_reset_pwd.setVisibility(View.GONE);
			messagetip
					.setText("\t\t滑动上面的图像设置密码,上图表示0-8九个数字,根据您滑动的先后顺序生成密码,密码生成后每次查看信息都需要输入正确的密码才能进入系统,请牢记自己的密码,当遗忘密码时请联系我们的工作人员,我们会尽快帮你找回密码");
		}
		btn_reset_pwd.setOnClickListener(this);
		btn_set_pwd.setOnClickListener(this);
		tel.setOnClickListener(this);
		new LockPatternUtils(this);
		lockPatternView.setOnPatternListener(new OnPatternListener() {

			public void onPatternStart() {

			}

			public void onPatternDetected(List<Cell> pattern) {
				// lockPatternView.setDisplayMode(DisplayMode.Animate);
				if (flag == true) {// 没点设置密码时
					String oldpwd = "";
					shp = getSharedPreferences("lock_pwd", 0);
					try {
						oldpwd = shp.getString("lock_pwd", "");
					} catch (Exception e) {
						e.printStackTrace();

					}
					if (oldpwd.equals("")) {
						// Log.e("lock", "密码为空");
						pwd = LockPatternUtils.patternToString(pattern);
						TelephonyManager mTelephonyMgr = (TelephonyManager) LockMainActivity.this
								.getSystemService(Context.TELEPHONY_SERVICE);
						String IMSI = mTelephonyMgr.getSubscriberId();
						postpwdtoservice(IMSI, pwd);
						// String a = LockPatternUtils.patternToString(pattern);
						// Editor editor = shp.edit();
						// editor.putString("lock_pwd", a);
						// editor.commit();
						// Log.e("lock", "输入密码" + a);

					} else {
						// Log.e("lock", "密码不为空");
						if (oldpwd.equals(Encryption.encode(LockPatternUtils
								.patternToString(pattern)))) 
							{// 输入密码相同
							// Log.e("lock", "密码相同");
							lockPatternView.setDisplayMode(DisplayMode.Correct);
							Intent intserv = new Intent(LockMainActivity.this,
									MessageService.class);
							intserv.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							LockMainActivity.this.startService(intserv);
							// Intent intent = new Intent(LockMainActivity.this,
							// Messageothernew.class);
							Intent intent = new Intent(LockMainActivity.this,
									MainTab.class);
							LockMainActivity.this.startActivity(intent);
							LockMainActivity.this.finish();
							overridePendingTransition(R.anim.slide_left_in,
									R.anim.slide_left_out);
						} else {
							lockPatternView.setDisplayMode(DisplayMode.Wrong);
							wrongcount--;
							if (wrongcount > 0 && wrongcount < 4)
								Toast.makeText(
										LockMainActivity.this,
										"您还有" + wrongcount + "次机会,"
												+ wrongcount + "次机会用完后,将退出系统",
										Toast.LENGTH_LONG).show();
							if (wrongcount < 1) {
								Toast.makeText(LockMainActivity.this,
										"抱歉,您的机会用完了,五秒后将退出系统",
										Toast.LENGTH_LONG).show();
								handlers.postDelayed(run, 5000);

							}
						}
					}
				}

			}

			public void onPatternCleared() {

			}

			public void onPatternCellAdded(List<Cell> pattern) {

			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			this.finish();
			System.exit(0);
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		//
		super.onDestroy();
		this.finish();
	}

	Runnable run = new Runnable() {

		@Override
		public void run() {
			//
			System.exit(0);
		}
	};
	Runnable r1 = new Runnable() {

		public void run() {
			if (result1.equals("1")) {
				// Toast.makeText(LockMainActivity.this, "密码设置成功",
				// Toast.LENGTH_LONG).show();
				Editor editor = shp.edit();
				editor.putString("lock_pwd", Encryption.encode(pwd));
				editor.commit();
				progress.dismiss();
				AlertDialog.Builder builder = new AlertDialog.Builder(
						LockMainActivity.this);
				builder.setCancelable(false);
				builder.setMessage("密码修改成功\n您的新密码为："
						+ pwd.replace(",", "").replace("[", "")
								.replace("]", "") + "请牢记");
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Intent intserv = new Intent(
										LockMainActivity.this,
										MessageService.class);
								intserv.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								LockMainActivity.this.startService(intserv);
								Intent intent = new Intent(
										LockMainActivity.this,
										MainTab.class);
								LockMainActivity.this.startActivity(intent);
								LockMainActivity.this.finish();
								overridePendingTransition(R.anim.slide_left_in,
										R.anim.slide_left_out);
							}
						}).create().show();
			} else {
				progress.dismiss();
				Toast.makeText(LockMainActivity.this, "密码修改失败,请检查网络",
						Toast.LENGTH_LONG).show();
			}
		}

	};
	Runnable r = new Runnable() {
		public void run() {
			if (result.equals("1")) 
			{
				Editor editor = shp.edit();
				editor.putString("lock_pwd", Encryption.encode(pwd));
				editor.commit();
				progress.dismiss();
				AlertDialog.Builder builder = new AlertDialog.Builder(
						LockMainActivity.this);
				builder.setCancelable(false);
				builder.setMessage("密码设置成功\n"
						+ "您的密码为:"
						+ pwd.replace(",", "").replace("[", "")
								.replace("]", "") + "请牢记");
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,int which) 
							{
								Intent intserv = new Intent(LockMainActivity.this,MessageService.class);
								intserv.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								LockMainActivity.this.startService(intserv);
								Intent intent = new Intent(LockMainActivity.this,MainTab.class);
								LockMainActivity.this.startActivity(intent);
								LockMainActivity.this.finish();
								overridePendingTransition(R.anim.slide_left_in,
										R.anim.slide_left_out);
							}
						}).create().show();
			} else 
			{
				progress.dismiss();
				Toast.makeText(LockMainActivity.this, "密码设置失败,请检查网络是否正确",
						Toast.LENGTH_LONG).show();
			}
		}
	};

	protected void postpwdtoservice(final String IMSI, final String a) {
		//
		progress = ProgressDialog.show(this, "请稍候", "密码保存中.....", true);
		progress.show();
		new Thread() {
			public void run() {
				result = "" + WebService.Savepwd(IMSI, a);
				handler.post(r);
			}
		}.start();
	}

	protected void postpwdtoservice1(final String IMSI, final String a) {
		progress = ProgressDialog.show(this, "请稍候", "密码更新中...", true);
		progress.show();
		new Thread() {
			public void run() {
				result1 = "" + WebService.Savepwd(IMSI, a);
				handler1.post(r1);
			}
		}.start();
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_set_pwd:
			Intent intent=new Intent(LockMainActivity.this,GesturePWDCreateActivity.class);
			startActivity(intent);
			break;
		case R.id.btn_reset_pwd:

			Editor editor = shp.edit();
			editor.putString("lock_pwd", "");
			editor.commit();
			Intent intent2 = new Intent(this, LoginActivity.class);
			intent2.putExtra("LastAc", "Lock");
			this.startActivity(intent2);
			//this.finish();
			break;
		case R.id.tel:
			AlertDialog.Builder builder = new AlertDialog.Builder(
					LockMainActivity.this);
			builder.setMessage("拨打电话到"
					+ tel.getText().toString().replace("技术支持:", "") + "?");
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							try {
								Intent phIntent = new Intent(
										"android.intent.action.CALL",
										Uri.parse("tel:"
												+ tel.getText().toString()
														.replace("技术支持:", "")));
								startActivity(phIntent);
							} catch (Exception e) {

								Toast.makeText(LockMainActivity.this, "调用电话失败",
										Toast.LENGTH_LONG).show();
							}
						}
					})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,int which) 
								{
									
								}

							}).create().show();

			break;
		}

	}
}
